package com.easymin.weixin.service.impl;

import com.easymin.weixin.entity.VCode;
import com.easymin.weixin.entity.VCodeCriteria;
import com.easymin.weixin.mapper.BaseMapper;
import com.easymin.weixin.mapper.VCodeMapper;
import com.easymin.weixin.service.VCodeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by shine on 15/9/28.
 */
@Service
public class DefaultVCodeService extends AbstractBaseService<VCode, VCodeCriteria, Long> implements VCodeService {

  @Autowired
  private VCodeMapper vCodeMapper;

  @Override
  public BaseMapper<VCode, VCodeCriteria, Long> getMapper() {

    return vCodeMapper;
  }

  @Override
  public VCode findBy(String appKey, String phone) {

    VCodeCriteria vCodeCriteria = new VCodeCriteria();
    vCodeCriteria.createCriteria()
            .andAppKeyEqualTo(appKey)
            .andPhoneEqualTo(phone);

    List<VCode> vCodes = vCodeMapper.selectByExample(vCodeCriteria);

    if (!CollectionUtils.isEmpty(vCodes)) {
      return vCodes.get(0);
    }

    return null;
  }

  @Override
  public int updateIngoreNull(VCode vCode) {
    vCode.setUpdated(new Date());
    return super.updateIngoreNull(vCode);
  }

  @Override
  public int insert(VCode vCode) {
    vCode.setCreated(new Date());
    vCode.setUpdated(new Date());
    vCode.setVersion(1);
    return super.insert(vCode);
  }

  @Override
  public int deleteBy(String appKey, String phone) {

    VCodeCriteria vCodeCriteria = new VCodeCriteria();
    vCodeCriteria.createCriteria()
            .andAppKeyEqualTo(appKey)
            .andPhoneEqualTo(phone);

    return vCodeMapper.deleteByExample(vCodeCriteria);
  }
}
